# -*- coding: utf-8 -*-
import sys, os, re, threading, time, smtplib
from datetime import datetime
from selenium import selenium
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

class KaiXin:
	log_file = "/home/fkong/test/kaixin.log"
	categories = [u"商业", u"娱乐休闲", u"交通", u"地产置业", u"奢侈品", u"科技产品", u"军事武器"]
	base_lines = {u"时尚公寓": [136, 164], 
				 u"公仔玩偶店": [100, 112], 
				 u"珍珠头冠": [118, 132]}
	buy_dict = {}
	sell_dict = {}
	
	def __init__(self):
		pass

	def start(self):
		self.selenium = selenium("localhost", 4444, "*firefox", "http://www.kaixin001.com")
		self.selenium.start()
		self.selenium.open("/")
		self.selenium.wait_for_page_to_load("60000")

		self.selenium.type("email", "kongxxcn@163.com")
		self.selenium.type("password", "platform")
		self.selenium.click("btn_dl")
		self.selenium.wait_for_page_to_load("60000")

		self.selenium.click(u"link=超级大亨")
		self.selenium.wait_for_page_to_load("60000")

		self.selenium.click(u"link=购买资产")
		self.selenium.wait_for_page_to_load("60000")

		self.listByCategorys()

		self.selenium.stop()

	def listByCategorys(self):
		for i in range(1, 10000):
			if os.path.exists(self.log_file):
				os.remove(self.log_file)
			self.buy_dict.clear()
			self.sell_dict.clear()

			for category in self.categories:
				try:
					self.listByCategory(category)
				except:
					pass

			if len(self.buy_dict) > 0 or len(self.sell_dict) > 0:
				s = "buy list\n"
				for name in self.buy_dict.keys():
					s += name + ": " + self.buy_dict[name] + "\n"
				s += "\n"
				s += "sell list\n"
				for name in self.sell_dict.keys():
					s += name + ": " + self.sell_dict[name] + "\n"
				s = s.encode("utf-8")
				f = open(self.log_file,"a")
				f.write(s)
				f.close()
				#self.send_mail("kaixin@localhost", ["xx@abc.com"], "list", "", [self.log_file], "localhost")

			time.sleep(60)

	def listByCategory(self, category):
		self.selenium.click(u"link="+category)
		self.selenium.wait_for_page_to_load("60000")

		count = self.selenium.get_xpath_count("//div[@class='list_zc']/ul")
		for i in range(1, int(count) + 1):
			name = self.selenium.get_text("//div[@class='list_zc']/ul["+str(i)+"]/li[2]")
			s_price = self.selenium.get_text("//div[@class='list_zc']/ul["+str(i)+"]/li[3]")
			i_price = s_price.rstrip(u"亿元").rstrip(u"万元").rstrip(u"元")
			s = name + ", " + i_price + "\n"
			s = s.encode( "utf-8" )
			#print s
			for base_line_name in self.base_lines.keys():
				if name == base_line_name and int(i_price) <= self.base_lines[base_line_name][0]:
					self.buy_dict[name] = i_price
				if name == base_line_name and int(i_price) >= self.base_lines[base_line_name][1]:
					self.sell_dict[name] = i_price

	def send_mail(self, send_from, send_to, subject, text, files=[], server="localhost"):
		assert type(send_to)==list
		assert type(files)==list

		msg = MIMEMultipart()
		msg['From'] = send_from
		msg['To'] = COMMASPACE.join(send_to)
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = subject

		msg.attach( MIMEText(text) )

		for f in files:
			part = MIMEBase('application', "octet-stream")
			part.set_payload(open(f,"rb").read())
			Encoders.encode_base64(part)
			part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
			msg.attach(part)

		smtp = smtplib.SMTP(server)
		smtp.sendmail(send_from, send_to, msg.as_string())
		smtp.close()

kaixin = KaiXin()
kaixin.start()




